<template>
  <el-dialog
    v-model="dialogVisible"
    title="修改标签颜色"
    width="500px"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <div class="color-picker-content">
      <!-- 当前标签预览 -->
      <div class="current-tag">
        <h4>当前标签</h4>
        <el-tag
          v-if="tag"
          :color="tag.color"
          :style="{ color: getTextColor(tag.color) }"
          class="tag-preview"
        >
          {{ tag.name }}
        </el-tag>
      </div>

      <!-- 新颜色预览 -->
      <div class="new-color">
        <h4>新颜色预览</h4>
        <el-tag
          v-if="tag"
          :color="selectedColor"
          :style="{ color: getTextColor(selectedColor) }"
          class="tag-preview"
        >
          {{ tag.name }}
        </el-tag>
      </div>

      <!-- 颜色选择器 -->
      <div class="color-selector">
        <h4>选择颜色</h4>
        <div class="color-picker-container">
          <el-color-picker
            v-model="selectedColor"
            :predefine="predefineColors"
            size="large"
            @change="handleColorChange"
          />
          <el-input
            v-model="selectedColor"
            placeholder="输入十六进制颜色码"
            style="width: 200px; margin-left: 16px"
            @input="handleColorInput"
          />
        </div>
      </div>

      <!-- 预设颜色 -->
      <div class="preset-colors">
        <h4>预设颜色</h4>
        <div class="color-grid">
          <div
            v-for="color in predefineColors"
            :key="color"
            class="color-item"
            :class="{ active: selectedColor === color }"
            :style="{ backgroundColor: color }"
            @click="selectPresetColor(color)"
          >
            <el-icon v-if="selectedColor === color" class="check-icon">
              <Check />
            </el-icon>
          </div>
        </div>
      </div>

      <!-- 随机颜色 -->
      <div class="random-color">
        <el-button @click="generateRandomColor">
          <el-icon><Refresh /></el-icon>
          随机生成
        </el-button>
        <el-button @click="generateColorByName">
          <el-icon><MagicStick /></el-icon>
          根据名称生成
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleConfirm">
          确认修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { Check, Refresh, MagicStick } from "@element-plus/icons-vue";
import {
  updateTagColorApi,
  type TagInfo,
  TagManagementUtils
} from "@/api/tag-management";

interface Props {
  visible: boolean;
  tag: TagInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  tag: null
});

const emit = defineEmits<{
  "update:visible": [value: boolean];
  confirm: [];
}>();

const dialogVisible = ref(false);
const selectedColor = ref("#1890ff");
const submitting = ref(false);

// 预定义颜色
const predefineColors = [
  "#f56c6c",
  "#e6a23c",
  "#67c23a",
  "#1890ff",
  "#722ed1",
  "#eb2f96",
  "#fa541c",
  "#fadb14",
  "#52c41a",
  "#13c2c2",
  "#2f54eb",
  "#722ed1",
  "#fa8c16",
  "#a0d911",
  "#36cfc9",
  "#ff4d4f",
  "#ff7a45",
  "#ffa940",
  "#ffec3d",
  "#bae637",
  "#73d13d",
  "#40a9ff",
  "#597ef7",
  "#9254de",
  "#f759ab"
];

// 监听对话框显示状态
watch(
  () => props.visible,
  newVal => {
    dialogVisible.value = newVal;
    if (newVal && props.tag) {
      selectedColor.value = props.tag.color || "#1890ff";
    }
  },
  { immediate: true }
);

watch(dialogVisible, newVal => {
  emit("update:visible", newVal);
});

// 方法
const getTextColor = (backgroundColor: string): string => {
  if (!backgroundColor) return "#000000";
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};

const handleColorChange = (value: string) => {
  // 如果是 rgba 格式，转换为16进制
  if (value && value.startsWith("rgba")) {
    selectedColor.value = convertRgbaToHex(value);
  } else {
    selectedColor.value = value;
  }
  console.log("颜色选择器变化:", {
    original: value,
    converted: selectedColor.value
  });
};

const handleColorInput = (value: string) => {
  // 如果是 rgba 格式，转换为16进制
  if (value && value.startsWith("rgba")) {
    selectedColor.value = convertRgbaToHex(value);
  } else {
    selectedColor.value = value;
  }
  console.log("颜色输入变化:", {
    original: value,
    converted: selectedColor.value
  });
};

// 将 rgba 颜色转换为16进制
const convertRgbaToHex = (rgba: string): string => {
  try {
    // 解析 rgba(r, g, b, a) 格式
    const match = rgba.match(
      /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/
    );
    if (!match) return rgba;

    const r = parseInt(match[1]);
    const g = parseInt(match[2]);
    const b = parseInt(match[3]);

    // 转换为16进制
    const toHex = (n: number) => {
      const hex = n.toString(16);
      return hex.length === 1 ? "0" + hex : hex;
    };

    const hexColor = `#${toHex(r)}${toHex(g)}${toHex(b)}`;
    console.log("RGBA转16进制:", { rgba, hex: hexColor });
    return hexColor;
  } catch (error) {
    console.error("颜色转换失败:", error);
    return rgba;
  }
};

const selectPresetColor = (color: string) => {
  selectedColor.value = color;
};

const generateRandomColor = () => {
  selectedColor.value = TagManagementUtils.generateRandomColor();
};

const generateColorByName = () => {
  if (props.tag) {
    selectedColor.value = TagManagementUtils.generateColorByName(
      props.tag.name
    );
  }
};

const handleConfirm = async () => {
  if (!props.tag) return;

  // 验证颜色格式
  const validation = TagManagementUtils.validateColor(selectedColor.value);
  if (!validation.valid) {
    ElMessage.error(validation.message);
    return;
  }

  submitting.value = true;
  try {
    const data = await updateTagColorApi(props.tag.id, selectedColor.value);

    if (data && data.code === 200) {
      ElMessage.success("颜色修改成功");
      emit("confirm");
      handleCancel();
    } else {
      ElMessage.error(data?.message || "颜色修改失败");
    }
  } catch (error) {
    console.error("修改颜色失败:", error);
    ElMessage.error("修改颜色失败");
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  dialogVisible.value = false;
};
</script>

<style scoped>
.color-picker-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.current-tag,
.new-color,
.color-selector,
.preset-colors {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.current-tag h4,
.new-color h4,
.color-selector h4,
.preset-colors h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.tag-preview {
  align-self: flex-start;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 500;
  border: none;
}

.color-picker-container {
  display: flex;
  align-items: center;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 8px;
  max-width: 400px;
}

.color-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.color-item:hover {
  border-color: #409eff;
  transform: scale(1.1);
}

.color-item.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgb(64 158 255 / 20%);
}

.check-icon {
  font-size: 16px;
  color: white;
  text-shadow: 0 1px 2px rgb(0 0 0 / 50%);
}

.random-color {
  display: flex;
  gap: 12px;
}

.dialog-footer {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
</style>
